package com.freely.web.action;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freely.domain.Group;
import com.freely.domain.Location;
import com.freely.domain.Message;
import com.freely.domain.ResponseMessage;
import com.freely.domain.User;
import com.freely.service.ChatGroupService;
import com.freely.service.MessageService;
import com.freely.service.UserService;
import com.freely.util.Base64Util;
import com.freely.util.CommonUtil;
import com.freely.util.HttpUtil;
import com.freely.util.JSONUtil;
import com.freely.util.ResponseMessageUtil;
import com.freely.util.ValidatorUtil;
import com.opensymphony.xwork2.ActionSupport;

public class ChatGroupAction extends ActionSupport {
	private ChatGroupService chatGroupService;
	private MessageService messageService;
	private UserService userService;

	public void setChatGroupService(ChatGroupService chatGroupService) {
		this.chatGroupService = chatGroupService;
	}

	public void setMessageService(MessageService messageService) {
		this.messageService = messageService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void test() {
		DetachedCriteria criteria = DetachedCriteria.forClass(Group.class);
		criteria.add(Restrictions.eq("group_account", "1234567890"));
		List<Group> list = chatGroupService.findByCondition(criteria);

		DetachedCriteria criteria1 = DetachedCriteria.forClass(User.class);
		criteria1.add(Restrictions.eq("user_forbidden", false));
		List<User> list1 = userService.findByCondition(criteria1);

		Group group = list.get(0);

		group.setGroup_create_date(new Date());
		group.getUsers().remove(list1.get(0));
		group.getUsers().add(list1.get(2));


		/*
		 * Group group = new Group(); group.setGroup_account("1472583694");
		 * group.setGroup_name("qunzu2"); group.setGroup_create_date(new Date());
		 * group.setGroup_forbidden(false); group.setGroup_image("e://1//1//2345.jpg");
		 * group.setGroup_sum(1); group.setGroup_notice("haha22"); group.setUser(user);
		 * group.getUsers().add(user);
		 * 
		 * chatGroupService.addChatGroup(group);
		 */

	}

	/**
	 * 搜索想要加入的群
	 * 
	 * @throws IOException
	 */
	public void searchGroup() throws IOException {
		JSONObject object = HttpUtil.parseJSON("不存在的群帐号，请重新输入");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		String group_account = object.getString("group_account");
		if (group_account == null || group_account.trim().length() == 0) {
			ResponseMessageUtil.response(false, "不存在的群帐号，请重新输入");
			return;
		}
		// 设置查询语句
		DetachedCriteria criteria = DetachedCriteria.forClass(Group.class);
		criteria.add(Restrictions.like("group_account", "%" + group_account + "%"));
		// 查询符合的数据
		List<Group> result = chatGroupService.findByCondition(criteria);
		if (result == null) {
			ResponseMessageUtil.response(false, "不存在的群帐号，请重新输入");
			return;
		}
		// 将群头像转化为base64字符串
		for (Group temp : result) {
			File file = new File(temp.getGroup_image());
			if (!file.exists()) {
				file = new File(CommonUtil.groupImageInitializationLocation);
			}

			byte[] imageData = FileUtils.readFileToByteArray(file);
			temp.setGroup_image(Base64Util.encode(imageData));
		}

		ResponseMessageUtil.response(true, JSON.toJSONString(result));
	}

	/**
	 * 申请入群
	 * 
	 * @throws IOException
	 */
	public void addGroup() throws IOException {
		JSONObject object = HttpUtil.parseJSON("错误的数据，请重新输入");
		if (object == null) {
			return;
		}
		// 验证输入的数据是否符合规则
		Long user_id = object.getLong("user_id");
		Long group_id = object.getLong("group_id");
		if (user_id == null || group_id == null) {
			ResponseMessageUtil.response(false, "错误的数据，请重新输入");
			return;
		}
		// 查询是否存在该用户
		DetachedCriteria criteriaUser = DetachedCriteria.forClass(User.class);
		criteriaUser.add(Restrictions.eq("user_id", user_id));
		List<User> resultUser = userService.findByCondition(criteriaUser);
		if (resultUser == null) {
			ResponseMessageUtil.response(false, "错误的数据，请重试");
			return;
		}
		User user = resultUser.get(0);
		// 查询是否存在该群
		DetachedCriteria criteriaGroup = DetachedCriteria.forClass(Group.class);
		criteriaGroup.add(Restrictions.eq("group_id", group_id));
		List<Group> resultGroup = chatGroupService.findByCondition(criteriaGroup);
		if (resultGroup == null) {
			ResponseMessageUtil.response(false, "不存在该群，请重新搜索");
			return;
		}
		// 查询该用户是否已加入该群
		Group group = resultGroup.get(0);
		if (group.getUsers().contains(user)) {
			ResponseMessageUtil.response(false, "您已加入该群组");
			return;
		}
		// 判断是否被禁用
		if (user.getUser_forbidden() || group.getGroup_forbidden()) {
			ResponseMessageUtil.response(false, "您或该群被禁用，无法加入");
			return;
		}
		// 存储消息通知
		Message messageNotice = new Message();
		messageNotice.setMessage_type(1);
		messageNotice.setMessage_result(0);
		messageNotice.setMessage_title("入群申请");
		messageNotice.setMessage_content("用户" + user.getUser_name() + "申请加入群" + group.getGroup_name());
		messageNotice.setMessage_send_time(new Date());
		messageNotice.setMessage_read(false);
		messageNotice.setReceiver(group.getGroup_admin());
		messageNotice.setGroup(group);

		// 发送消息通知给群主
		// messageService.sendMessage(messageNotice);

		ResponseMessageUtil.response(true, "申请成功，请等待审核");
	}

	/**
	 * 群员退出群
	 * 
	 * @throws IOException
	 */
	public void exitGroup() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，退群失败");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		Long group_id = object.getLong("group_id");
		Long user_id = object.getLong("user_id");
		if (group_id == null || user_id == null) {
			ResponseMessageUtil.response(false, "无效的数据，退群失败");
			return;
		}
		// 查询是否存在该群
		DetachedCriteria criteria = DetachedCriteria.forClass(Group.class);
		criteria.add(Restrictions.eq("group_id", group_id));
		List<Group> result = chatGroupService.findByCondition(criteria);
		if (result == null) {
			ResponseMessageUtil.response(false, "不存在该群组");
			return;
		}
		Group group = result.get(0);
		// 查询该群是否存在该用户
		Set<User> users = group.getUsers();
		User user = null;
		for (User temp : users) {
			if (temp.getUser_id().equals(user_id)) {
				user = temp;
				break;
			}
		}
		if (user == null) {
			ResponseMessageUtil.response(false, "该群不存在该用户");
			return;
		}
		// 判断是否被禁用
		if (user.getUser_forbidden()) {
			ResponseMessageUtil.response(false, "您已被禁用，无法退群");
			return;
		}
		// 移除该用户
		group.getUsers().remove(user);
		try {
			chatGroupService.updateGroupMember(group,false);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseMessageUtil.response(false, "退出失败");
			return;
		}
		ResponseMessageUtil.response(true, "退出成功");
	}

	/**
	 * 查询已加入的群
	 * 
	 * @throws IOException
	 */
	public void queryAllAddedGroup() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，查询失败");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		Long user_id = object.getLong("user_id");
		if (user_id == null) {
			ResponseMessageUtil.response(false, "无效的数据，查询失败");
			return;
		}
		// 查询是否存在该用户
		DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
		criteria.add(Restrictions.eq("user_id", user_id));
		List<User> result = userService.findByCondition(criteria);
		if (result == null) {
			ResponseMessageUtil.response(false, "不存在的用户，查询失败");
			return;
		}
		User user = result.get(0);
		Set<Group> groups = user.getGroups();
		// 将群图片转化为base64编码字符串
		for (Group temp : groups) {
			String path = temp.getGroup_image();
			File file = new File(path);
			if (!file.exists()) {
				file = new File(CommonUtil.groupImageInitializationLocation);
			}

			byte[] imageData = FileUtils.readFileToByteArray(file);
			temp.setGroup_image(Base64Util.encode(imageData));
		}
		ResponseMessageUtil.response(true, JSON.toJSONString(groups));
	}

	/**
	 * 查看群成员位置信息
	 * 
	 * @throws IOException
	 */
	public void getMemberLocation() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，获取失败");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		Long group_id = object.getLong("group_id");
		if (group_id == null) {
			ResponseMessageUtil.response(false, "无效的数据，查询失败");
			return;
		}
		// 查询是否存在该群
		DetachedCriteria criteria = DetachedCriteria.forClass(Group.class);
		criteria.add(Restrictions.eq("group_id", group_id));
		List<Group> result = chatGroupService.findByCondition(criteria);
		if (result == null) {
			ResponseMessageUtil.response(false, "无效的数据，查询失败");
			return;
		}
		Group group = result.get(0);
		// 判断该群是否被禁用
		if (group.getGroup_forbidden()) {
			ResponseMessageUtil.response(false, "该群被禁用,无法获取群员位置信息");
			return;
		}
		// 将群员的信息存储在集合中
		List<String> data = new ArrayList<>();
		ServletContext context = ServletActionContext.getServletContext();
		for (User temp : group.getUsers()) {
			if (!temp.getUser_online() || temp.getUser_forbidden()) {
				continue;
			}
			// 过滤不需要的字段
			JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(temp,
					JSONUtil.jsonFilter("user_password", "user_email", "user_phone", "user_last_login_time",
							"user_last_update_time", "user_online", "user_forbidden", "groups")));
			// 将群员头像转化为base64字符串
			String path = jsonObject.getString("user_image");
			File file = new File(path);
			if (!file.exists()) {
				file = new File(CommonUtil.userImageInitializationLocation);
			}

			byte[] imageData = FileUtils.readFileToByteArray(file);
			jsonObject.put("user_image", Base64Util.encode(imageData));
			// 存储群员的位置信息
			Location location = (Location) context.getAttribute(jsonObject.getString("user_id"));
			jsonObject.put("location_longitude", location.getLocation_longitude());
			jsonObject.put("location_latitude", location.getLocation_latitude());
			// 存储在集合中
			data.add(jsonObject.toJSONString());
		}
		ResponseMessageUtil.response(true, JSON.toJSONString(data));
	}

	/**
	 * 邀请群成员
	 * 
	 * @throws IOException
	 */
	public void inviteMember() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，邀请失败");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		Long group_id = object.getLong("group_id");
		Long inviter_id = object.getLong("inviter_id");
		Long invitee_id = object.getLong("invitee_id");
		if (group_id == null || inviter_id == null || invitee_id == null) {
			ResponseMessageUtil.response(false, "无效的数据，邀请失败");
			return;
		}
		// 查询是否存在该群
		DetachedCriteria criteriaGroup = DetachedCriteria.forClass(Group.class);
		criteriaGroup.add(Restrictions.eq("group_id", group_id));
		List<Group> resultGroup = chatGroupService.findByCondition(criteriaGroup);
		if (resultGroup == null) {
			ResponseMessageUtil.response(false, "不存在该群,邀请失败");
			return;
		}
		Group group = resultGroup.get(0);
		// 判断该群是否被禁用
		if (group.getGroup_forbidden()) {
			ResponseMessageUtil.response(false, "该群被禁用,无法邀请");
			return;
		}
		// 判断邀请人是否存在
		DetachedCriteria criteriaInviter = DetachedCriteria.forClass(User.class);
		criteriaInviter.add(Restrictions.eq("user_id", inviter_id));
		List<User> resultInviter = userService.findByCondition(criteriaInviter);
		if (resultInviter == null) {
			ResponseMessageUtil.response(false, "不存在该用户,邀请失败");
			return;
		}
		User inviter = resultInviter.get(0);
		// 判断邀请人是否被禁用
		if (inviter.getUser_forbidden()) {
			ResponseMessageUtil.response(false, "邀请人被禁用,邀请失败");
			return;
		}
		// 判断邀请人是否在该群
		if (!group.getUsers().contains(inviter)) {
			ResponseMessageUtil.response(false, "邀请人不存在该群,邀请失败");
			return;
		}
		// 判断被邀请人是否存在
		DetachedCriteria criteriaInvitee = DetachedCriteria.forClass(User.class);
		criteriaInviter.add(Restrictions.eq("user_id", invitee_id));
		List<User> resultInvitee = userService.findByCondition(criteriaInvitee);
		if (resultInvitee == null) {
			ResponseMessageUtil.response(false, "不存在该用户,邀请失败");
			return;
		}
		User invitee = resultInvitee.get(0);
		// 判断被邀请人是否被禁用
		if (invitee.getUser_forbidden()) {
			ResponseMessageUtil.response(false, "被邀请人被禁用,邀请失败");
			return;
		}
		// 判断被邀请人是否在该群
		if (group.getUsers().contains(invitee)) {
			ResponseMessageUtil.response(false, "邀请人已在该群,邀请失败");
			return;
		}
		// 添加被邀请人到该群
		group.getUsers().add(invitee);
		try {
			chatGroupService.updateGroupMember(group,true);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseMessageUtil.response(false, "邀请失败");
			return;
		}
		ResponseMessageUtil.response(true, "邀请成功");
	}

	/**
	 * 查看群成员
	 * 
	 * @throws IOException
	 */
	public void queryAllMember() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，查看失败");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		Long group_id = object.getLong("group_id");
		if (group_id == null) {
			ResponseMessageUtil.response(false, "无效的数据，查看失败");
			return;
		}
		// 判断是否存在该群
		DetachedCriteria criteria = DetachedCriteria.forClass(Group.class);
		criteria.add(Restrictions.eq("group_id", group_id));
		List<Group> result = chatGroupService.findByCondition(criteria);
		if (result == null) {
			ResponseMessageUtil.response(false, "不存在该群，查看失败");
			return;
		}
		Group group = result.get(0);
		// 判断该群是否被禁用
		if (group.getGroup_forbidden()) {
			ResponseMessageUtil.response(false, "该群被禁用，查看失败");
			return;
		}
		// 将群员存储在集合中
		List<String> data = new ArrayList<>();
		for (User temp : group.getUsers()) {
			// 过滤不需要的字段
			JSONObject jsonObject = JSON.parseObject(
					JSON.toJSONString(temp, JSONUtil.jsonFilter("user_password", "user_email", "user_last_login_time",
							"user_last_update_time", "user_online", "user_forbidden", "groups")));
			// 将头像转化为base64字符串
			String path = jsonObject.getString("user_image");
			File file = new File(path);
			if (!file.exists()) {
				file = new File(CommonUtil.userImageInitializationLocation);
			}

			byte[] imageData = FileUtils.readFileToByteArray(file);
			jsonObject.put("user_image", Base64Util.encode(imageData));
			// 存储到集合中
			data.add(jsonObject.toJSONString());
		}
		ResponseMessageUtil.response(true, JSON.toJSONString(data));
	}

	/**
	 * 搜索已加入群
	 * 
	 * @throws IOException
	 */
	public void queryJoinedGroup() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，查看失败");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		String group_account = object.getString("group_account");
		Long user_id = object.getLong("user_id");
		if (group_account == null || group_account.trim().length() == 0 || user_id == null) {
			ResponseMessageUtil.response(false, "无效的数据，搜索失败");
			return;
		}
		// 判断是否存在该用户
		DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
		criteria.add(Restrictions.eq("user_id", user_id));
		List<User> result = userService.findByCondition(criteria);
		if (result == null) {
			ResponseMessageUtil.response(false, "无效的数据，搜索失败");
			return;
		}
		User user = result.get(0);
		// 判断用户是否被禁用
		if (user.getUser_forbidden()) {
			ResponseMessageUtil.response(false, "该用户被禁用，搜索失败");
			return;
		}
		List<String> data = new ArrayList<>();
		// 将数据存储在集合中
		for (Group temp : user.getGroups()) {
			if (temp.getGroup_account().matches("*" + group_account + "*")) {
				// 将群头像转化为base64字符串
				String path = temp.getGroup_image();
				File file = new File(path);
				if (!file.exists()) {
					file = new File(CommonUtil.groupImageInitializationLocation);
				}

				byte[] imageData = FileUtils.readFileToByteArray(file);
				temp.setGroup_image(Base64Util.encode(imageData));
				// 将数据存储到集合中
				data.add(JSON.toJSONString(temp));
			}
		}
		ResponseMessageUtil.response(true, JSON.toJSONString(data));
	}

	/**
	 * 搜索群成员
	 * 
	 * @throws IOException
	 */
	public void queryMember() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，搜索失败");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		Long group_id = object.getLong("group_id");
		String user_name = object.getString("user_name");
		if (group_id == null || user_name == null || user_name.trim().length() == 0) {
			ResponseMessageUtil.response(false, "无效的数据，搜索失败");
			return;
		}
		// 判断是否存在该群
		DetachedCriteria criteria = DetachedCriteria.forClass(Group.class);
		criteria.add(Restrictions.eq("group_id", group_id));
		List<Group> result = chatGroupService.findByCondition(criteria);
		if (result == null) {
			ResponseMessageUtil.response(false, "不存在该群，搜索失败");
			return;
		}
		Group group = result.get(0);
		if (group.getGroup_forbidden()) {
			ResponseMessageUtil.response(false, "该群被禁用，搜索失败");
			return;
		}
		// 将与搜索内容相似的群成员存储在集合中
		List<String> data = new ArrayList<>();
		for (User temp : group.getUsers()) {
			if (temp.getUser_name().matches("*" + user_name + "*")) {
				// 过滤掉不需要的字段
				JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(temp,
						JSONUtil.jsonFilter("user_password", "user_email", "user_last_login_time",
								"user_last_update_time", "user_forbidden", "user_online", "groups")));
				// 将头像转化为base64字符串
				String path = temp.getUser_image();
				File file = new File(path);
				if (!file.exists()) {
					file = new File(CommonUtil.userImageInitializationLocation);
				}

				byte[] imageData = FileUtils.readFileToByteArray(file);
				jsonObject.put("user_image", Base64Util.encode(imageData));
				// 将数据存储到集合中
				data.add(jsonObject.toJSONString());
			}
		}
		ResponseMessageUtil.response(true, JSON.toJSONString(data));
	}

	/**
	 * 搜索群员位置
	 * 
	 * @throws IOException
	 */
	public void queryMemberLocation() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，搜索失败");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		Long group_id = object.getLong("group_id");
		String user_name = object.getString("user_name");
		if (group_id == null || user_name == null || user_name.trim().length() == 0) {
			ResponseMessageUtil.response(false, "无效的数据，搜索失败");
			return;
		}
		// 判断是否存在该群
		DetachedCriteria criteriaGroup = DetachedCriteria.forClass(Group.class);
		criteriaGroup.add(Restrictions.eq("group_id", group_id));
		List<Group> resultGroup = chatGroupService.findByCondition(criteriaGroup);
		if (resultGroup == null) {
			ResponseMessageUtil.response(false, "不存在该群，搜索失败");
			return;
		}
		Group group = resultGroup.get(0);
		// 判断该群是否被禁用
		if (group.getGroup_forbidden()) {
			ResponseMessageUtil.response(false, "该群被禁用,无法搜索");
			return;
		}
		// 判断是否存在该用户
		DetachedCriteria criteriaUser = DetachedCriteria.forClass(User.class);
		criteriaUser.add(Restrictions.eq("user_name", user_name));
		List<User> resultUser = userService.findByCondition(criteriaUser);
		if (resultUser == null) {
			ResponseMessageUtil.response(false, "不存在该用户");
			return;
		}
		User user = resultUser.get(0);
		// 判断用户是否被禁用
		if (!user.getUser_forbidden()) {
			ResponseMessageUtil.response(false, "该用户被禁用，无法获取位置");
			return;
		}
		// 判断用户是否在线
		if (!user.getUser_online()) {
			ResponseMessageUtil.response(false, "该用户不在线，无法获取最新位置");
			return;
		}

		// 判断该群是否存在该用户
		for (User temp : group.getUsers()) {
			if (temp.equals(user)) {
				// 过滤不需要的字段
				JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(temp,
						JSONUtil.jsonFilter("user_password", "user_email", "user_phone", "user_last_login_time",
								"user_last_update_time", "user_online", "user_forbidden", "groups")));
				// 将群员头像转化为base64字符串
				String path = jsonObject.getString("user_image");
				File file = new File(path);
				if (!file.exists()) {
					file = new File(CommonUtil.userImageInitializationLocation);
				}

				byte[] imageData = FileUtils.readFileToByteArray(file);
				jsonObject.put("user_image", Base64Util.encode(imageData));
				// 存储群员的位置信息
				Location location = (Location) ServletActionContext.getServletContext()
						.getAttribute(jsonObject.getString("user_id"));
				jsonObject.put("location_longitude", location.getLocation_longitude());
				jsonObject.put("location_latitude", location.getLocation_latitude());
				ResponseMessageUtil.response(true, jsonObject.toJSONString());
				return;
			}
		}
		ResponseMessageUtil.response(false, "该群不存在该用户");
	}

	/**
	 * 创建群
	 * 
	 * @throws IOException
	 */
	public void createGroup() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，创建失败");
		if (object == null) {
			return;
		}
		// 判断是否存在该用户
		Long group_admin = object.getLong("group_admin");
		if (group_admin == null) {
			ResponseMessageUtil.response(false, "不存在该用户，创建失败");
			return;
		}
		DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
		criteria.add(Restrictions.eq("group_admin", group_admin));
		List<User> result = userService.findByCondition(criteria);
		if (result == null) {
			ResponseMessageUtil.response(false, "不存在该用户，创建失败");
			return;
		}
		User user = result.get(0);
		// 判断用户是否被禁用
		if (user.getUser_forbidden()) {
			ResponseMessageUtil.response(false, "您已被禁用，创建失败");
			return;
		}
		// 判断数据是否符合规则
		Group validatorGroup = object.toJavaObject(Group.class);
		String validator = ValidatorUtil.validate(validatorGroup);
		JSONObject validatorObj = new JSONObject();
		if (validator != null) {
			validatorObj = JSONObject.parseObject(validator);
		}

		// 判断群头像是否符合规则
		String encodeImage = object.getString("group_image");
		byte[] decodeImage = null;
		// 判断是否更新头像并且更新的头像是否符合规则,符合则存储新头像的路径
		if (encodeImage != null) {
			decodeImage = Base64Util.decode(encodeImage);
			if ((decodeImage[0] != -1 && decodeImage[1] != -40) || (decodeImage.length > CommonUtil.imageMaxSize)) {
				validatorObj.put("group_image", "头像格式只支持jpg格式，并且大小不可超过100kb");
			} else {
				String fileName = CommonUtil.getUUID() + ".jpg";
				String hex = Integer.toHexString(fileName.hashCode());
				File parentFile = new File(CommonUtil.imagePath, hex.charAt(0) + File.separator + hex.charAt(1));
				if (!parentFile.exists()) {
					parentFile.mkdirs();
				}
				File image = new File(parentFile, fileName);
				validatorGroup.setGroup_image(image.getAbsolutePath());
			}
		} else {
			validatorGroup.setGroup_image(CommonUtil.groupImageInitializationLocation);
		}
		// 如果格式错误则更新失败
		if (validatorObj.size() > 0) {
			ResponseMessageUtil.response(false, JSON.toJSONString(validatorObj));
			return;
		}

		// 创建群实体
		validatorGroup.setGroup_admin(user);
		validatorGroup.getUsers().add(user);
		validatorGroup.setGroup_account(CommonUtil.randomNumber(10));
		validatorGroup.setGroup_sum(1);
		validatorGroup.setGroup_create_date(new Date());
		validatorGroup.setGroup_forbidden(false);
		// 向数据库中插入数据
		try {
			chatGroupService.addChatGroup(validatorGroup);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseMessageUtil.response(false, "创建失败");
			return;
		}
		// 将创建的群返回
		if(encodeImage == null) {
			File file = new File(validatorGroup.getGroup_image());
			byte[] imageData = FileUtils.readFileToByteArray(file);
			validatorGroup.setGroup_image(Base64Util.encode(imageData));
		}else {
			validatorGroup.setGroup_image(encodeImage);
		}
		ResponseMessageUtil.response(true, JSON.toJSONString(validatorGroup));
	}

	/**
	 * 删除群
	 * 
	 * @throws IOException
	 */
	public void deleteGroup() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，删除失败");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		Long group_id = object.getLong("group_id");
		Long group_admin = object.getLong("group_admin");
		if (group_id == null || group_admin == null) {
			ResponseMessageUtil.response(false, "数据缺失，删除失败");
			return;
		}
		// 判断是否存在该群
		DetachedCriteria criteria = DetachedCriteria.forClass(Group.class);
		criteria.add(Restrictions.eq("group_id", group_id));
		List<Group> result = chatGroupService.findByCondition(criteria);
		if (result == null) {
			ResponseMessageUtil.response(false, "不存在该群，删除失败");
			return;
		}
		Group group = result.get(0);
		// 判断该用户是不是群主
		if (!group.getGroup_admin().getUser_id().equals(group_admin)) {
			ResponseMessageUtil.response(false, "您不是群主，无法删除");
			return;
		}
		// 判断是否被禁用
		if (group.getGroup_admin().getUser_forbidden() || group.getGroup_forbidden()) {
			ResponseMessageUtil.response(false, "您或该群已被禁用，无法删除");
			return;
		}
		// 删除该群及群成员
		try {
			chatGroupService.deleteGroup(group);
			// 删除群头像文件
			String path = group.getGroup_image();
			if(!path.equals(CommonUtil.groupImageInitializationLocation)) {
				File file = new File(path);
				if(file.exists()) {
					file.delete();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ResponseMessageUtil.response(false, "删除群失败");
			return;
		}
		ResponseMessageUtil.response(false, "删除群成功");
	}

	/**
	 * 修改群公告
	 * 
	 * @throws IOException
	 */
	public void updateGroupNotice() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，修改失败");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		Long group_id = object.getLong("group_id");
		Long group_admin = object.getLong("group_admin");
		String group_notice = object.getString("group_notice");
		if (group_id == null || group_admin == null || group_notice == null) {
			ResponseMessageUtil.response(false, "无效的数据，修改失败");
			return;
		}
		if (group_notice.length() > 100) {
			ResponseMessageUtil.response(false, "群公告长度不可超过100，修改失败");
			return;
		}
		// 判断是否存在该群
		DetachedCriteria criteria = DetachedCriteria.forClass(Group.class);
		criteria.add(Restrictions.eq("group_id", group_id));
		List<Group> result = chatGroupService.findByCondition(criteria);
		if (result == null) {
			ResponseMessageUtil.response(false, "不存在该群");
			return;
		}
		Group group = result.get(0);
		// 判断该用户是否是群主
		if (!group.getGroup_admin().getUser_id().equals(group_admin)) {
			ResponseMessageUtil.response(false, "您不是群主，无法修改群公告");
			return;
		}
		// 判断该群是否被禁用
		if (group.getGroup_admin().getUser_forbidden() || group.getGroup_forbidden()) {
			ResponseMessageUtil.response(false, "您或该群已被禁用，无法修改群公告");
			return;
		}
		// 配置更新语句
		JSONObject modifyObj = new JSONObject();
		JSONObject conditionObj = new JSONObject();
		modifyObj.put("group_notice", group_notice);
		conditionObj.put("group_id", group_id);
		// 更新群公告
		int nums = chatGroupService.update(modifyObj, conditionObj);
		if (nums <= 0) {
			ResponseMessageUtil.response(false, "修改失败");
			return;
		}
		ResponseMessageUtil.response(true, "修改成功");
	}

	/**
	 * 修改群名
	 * 
	 * @throws IOException
	 */
	public void updateGroupName() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，修改失败");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		Long group_id = object.getLong("group_id");
		Long group_admin = object.getLong("group_admin");
		String group_name = object.getString("group_name");
		if (group_id == null || group_admin == null || group_name == null) {
			ResponseMessageUtil.response(false, "无效的数据，修改失败");
			return;
		}
		if (group_name.trim().length() == 0 || group_name.trim().length() > 20) {
			ResponseMessageUtil.response(false, "群名称长度限制在1-20，修改失败");
			return;
		}
		// 判断是否存在该群
		DetachedCriteria criteria = DetachedCriteria.forClass(Group.class);
		criteria.add(Restrictions.eq("group_id", group_id));
		List<Group> result = chatGroupService.findByCondition(criteria);
		if (result == null) {
			ResponseMessageUtil.response(false, "不存在该群");
			return;
		}
		Group group = result.get(0);
		// 判断该用户是否是群主
		if (!group.getGroup_admin().getUser_id().equals(group_admin)) {
			ResponseMessageUtil.response(false, "您不是群主，没有权限修改群名");
			return;
		}
		// 判断该群是否被禁用
		if (group.getGroup_admin().getUser_forbidden() || group.getGroup_forbidden()) {
			ResponseMessageUtil.response(false, "您已被禁用，无法修改群名");
			return;
		}
		// 配置更新语句
		JSONObject conditionObj = new JSONObject();
		conditionObj.put("group_id", Long.parseLong((String) object.remove("group_id")));
		int nums = chatGroupService.update(object, conditionObj);
		if (nums <= 0) {
			ResponseMessageUtil.response(false, "修改失败");
			return;
		}
		ResponseMessageUtil.response(true, "修改成功");
	}

	/**
	 * 移除指定群成员
	 * 
	 * @throws IOException
	 */
	public void deleteMember() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，修改失败");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		Long group_id = object.getLong("group_id");
		Long group_admin = object.getLong("group_admin");
		Long user_id = object.getLong("user_id");
		if (group_id == null || group_admin == null || user_id == null) {
			ResponseMessageUtil.response(false, "无效的数据，移除成员失败");
			return;
		}
		// 判断是否存在该群
		DetachedCriteria criteria = DetachedCriteria.forClass(Group.class);
		criteria.add(Restrictions.eq("group_id", group_id));
		List<Group> result = chatGroupService.findByCondition(criteria);
		if (result == null) {
			ResponseMessageUtil.response(false, "不存在该群，移除失败");
			return;
		}
		Group group = result.get(0);
		// 判断该群是否被禁用
		if (group.getGroup_forbidden()) {
			ResponseMessageUtil.response(false, "该群被禁用，无法移除成员");
			return;
		}
		// 判断该用户是否是群主
		if (!group.getGroup_admin().getUser_id().equals(group_admin)) {
			ResponseMessageUtil.response(false, "您不是群主，无法移除成员");
			return;
		}
		// 判断该用户是否被禁用
		if (group.getGroup_admin().getUser_forbidden()) {
			ResponseMessageUtil.response(false, "您已被禁用，无法移除成员");
			return;
		}
		// 判断该成员是否在该群
		User user = null;
		for (User temp : group.getUsers()) {
			if (temp.getUser_id().equals(user_id)) {
				user = temp;
				break;
			}
		}
		if (user == null) {
			ResponseMessageUtil.response(false, "该用户不在该群，移除失败");
			return;
		}

		if (group.getGroup_admin().getUser_id().equals(user.getUser_id())) {
			// 删除群
			try {
				chatGroupService.deleteGroup(group);
			} catch (Exception e) {
				e.printStackTrace();
				ResponseMessageUtil.response(false, "删除群失败");
			}
		} else {
			// 移除该成员
			group.getUsers().remove(user);
			try {
				chatGroupService.updateGroupMember(group,false);
			} catch (Exception e) {
				e.printStackTrace();
				ResponseMessageUtil.response(false, "移除该成员失败");
			}
		}
	}

	/**
	 * 加入群通过
	 * 
	 * @throws IOException
	 */
	public void passJoinGroup() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据，加入群失败");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		Long group_id = object.getLong("group_id");
		Long group_admin = object.getLong("group_admin");
		Long user_id = object.getLong("user_id");
		if (group_id == null || group_admin == null || user_id == null) {
			ResponseMessageUtil.response(false, "无效的数据，加入群失败");
			return;
		}
		// 判断是否存在该群
		DetachedCriteria criteriaGroup = DetachedCriteria.forClass(Group.class);
		criteriaGroup.add(Restrictions.eq("group_id", group_id));
		List<Group> resultGroup = chatGroupService.findByCondition(criteriaGroup);
		if (resultGroup == null) {
			ResponseMessageUtil.response(false, "不存在该群，加入群失败");
			return;
		}
		Group group = resultGroup.get(0);
		// 判断该群是否被禁用
		if (group.getGroup_forbidden()) {
			ResponseMessageUtil.response(false, "该群被禁用，加入群失败");
			return;
		}
		// 判断该用户是否是群主
		if (!group.getGroup_admin().getUser_id().equals(group_admin)) {
			ResponseMessageUtil.response(false, "您不是群主，无法审核该请求");
			return;
		}
		// 判断群主是否被禁用
		if (group.getGroup_admin().getUser_forbidden()) {
			ResponseMessageUtil.response(false, "您已被禁用，无法审核请求");
			return;
		}
		// 判断该成员是否在该群
		for (User temp : group.getUsers()) {
			if (temp.getUser_id().equals(user_id)) {
				ResponseMessageUtil.response(false, "该用户已在该群，加入失败");
				return;
			}
		}
		// 判断是否存在该用户
		DetachedCriteria criteriaUser = DetachedCriteria.forClass(User.class);
		criteriaUser.add(Restrictions.eq("user_id", user_id));
		List<User> resultUser = userService.findByCondition(criteriaUser);
		if (resultUser == null) {
			ResponseMessageUtil.response(false, "不存在该用户，加入失败");
			return;
		}
		User user = resultUser.get(0);
		// 判断该用户是否被禁用
		if (user.getUser_forbidden()) {
			ResponseMessageUtil.response(false, "该用户已被禁用，加入失败");
			return;
		}
		// 添加该用户到该群
		group.getUsers().add(user);
		try {
			chatGroupService.updateGroupMember(group,true);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseMessageUtil.response(false, "加入失败");
			return;
		}
		ResponseMessageUtil.response(true, "加入成功");
	}

	/**
	 * 同意入群邀请
	 * 
	 * @throws IOException
	 */
	public void agreeJoinGroup() throws IOException {
		JSONObject object = HttpUtil.parseJSON("无效的数据");
		if (object == null) {
			return;
		}
		// 判断数据是否符合规则
		Long group_id = object.getLong("group_id");
		Long user_id = object.getLong("user_id");
		if (group_id == null || user_id == null) {
			ResponseMessageUtil.response(false, "无效的数据");
			return;
		}
		// 判断是否存在该群
		DetachedCriteria criteriaGroup = DetachedCriteria.forClass(Group.class);
		criteriaGroup.add(Restrictions.eq("group_id", group_id));
		List<Group> resultGroup = chatGroupService.findByCondition(criteriaGroup);
		if (resultGroup == null) {
			ResponseMessageUtil.response(false, "不存在该群，加入群失败");
			return;
		}
		Group group = resultGroup.get(0);
		// 判断该群是否被禁用
		if (group.getGroup_forbidden()) {
			ResponseMessageUtil.response(false, "该群被禁用，加入群失败");
			return;
		}
		// 判断该成员是否在该群
		for (User temp : group.getUsers()) {
			if (temp.getUser_id().equals(user_id)) {
				ResponseMessageUtil.response(false, "该用户已在该群，加入失败");
				return;
			}
		}
		// 判断是否存在该用户
		DetachedCriteria criteriaUser = DetachedCriteria.forClass(User.class);
		criteriaUser.add(Restrictions.eq("user_id", user_id));
		List<User> resultUser = userService.findByCondition(criteriaUser);
		if (resultUser == null) {
			ResponseMessageUtil.response(false, "不存在该用户，加入失败");
			return;
		}
		User user = resultUser.get(0);
		// 判断该用户是否被禁用
		if (user.getUser_forbidden()) {
			ResponseMessageUtil.response(false, "该用户已被禁用，加入失败");
			return;
		}
		// 添加该用户到该群
		group.getUsers().add(user);
		try {
			chatGroupService.updateGroupMember(group,true);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseMessageUtil.response(false, "加入失败");
			return;
		}
		// 将群头像转化为base64字符串
		File file = new File(group.getGroup_image());
		if (!file.exists()) {
			file = new File(CommonUtil.groupImageInitializationLocation);
		}

		byte[] imageData = FileUtils.readFileToByteArray(file);
		group.setGroup_image(Base64Util.encode(imageData));
		// 将该群数据返回
		ResponseMessageUtil.response(true, JSON.toJSONString(group));
	}
}
